package com.imoney.framework.base.pagination.impl;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;

import com.imoney.framework.base.pagination.IPage;


/**
 * 
 * Description: <BR>
 * 分页实现类
 * 
 * @author robin wu CreateTime: Jul 13, 2010
 */
public class Page<T> implements IPage<T> {

	private static final long serialVersionUID = -2463073478584913302L;

	// the record in page
	private int size;
	
	// page index
	private int index;
	
	// the record total
	private long total;
	
	private long totalRecord;
	
	private String url;
	
	private Collection<T> data;
	
	public Page() {		
	}

	public Page(Collection<T> data, long totalRecord, int index, int size) {
		this.data = (data == null ? new ArrayList<T>(0) : data);
		this.totalRecord = totalRecord;
		this.size = size;
		this.index = index;
		this.total=(totalRecord-1)/size+1;
	}
	
	
	public void setTotalRecord(long totalRecord) {
		this.totalRecord = totalRecord;
	}	

	public long getTotalRecord() {
		return totalRecord;
	}

	public void setTotal(int total){
		this.total=total;
	}

	public int getSize() {
		return size;
	}
	
	public long getTotal() {
		return total;
	}

	public int getIndex() {
		return index;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Collection<T> getData() {
		return data;
	}
	
	@Override
	public String toString() {
		StringBuilder buf = new StringBuilder();
		Method[] methods = this.getClass().getMethods();
		boolean isFirst = true;
		for (int i = 0, n = methods.length; i < n; i++) {
			try {
				Method method = methods[i];
				if ((method.getModifiers() & Modifier.PUBLIC) == 1
						&& method.getDeclaringClass() != Object.class
						&& (method.getParameterTypes() == null || method
								.getParameterTypes().length == 0)) {
					String methodName = method.getName();
					String property = null;
					if (methodName.startsWith("get")) {
						property = methodName.substring(3, 4).toLowerCase()
								+ methodName.substring(4);
					} else if (methodName.startsWith("is")) {
						property = methodName.substring(2, 3).toLowerCase()
								+ methodName.substring(3);
					}
					if (property != null) {
						Object value = method.invoke(this, new Object[0]);
						if (isFirst)
							isFirst = false;
						else
							buf.append(",");
						buf.append(property);
						buf.append(":");
						if (value instanceof String)
							buf.append("\"");
						buf.append(value);
						if (value instanceof String)
							buf.append("\"");
					}
				}
			} catch (Exception e) {
				// ignore
			}
		}
		return "{" + buf.toString() + "}";
	}

}
